package by.grsu.bso.persistence.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import by.grsu.bso.model.Category;
import by.grsu.bso.persistence.base.ICategoryDAO;
import by.grsu.bso.persistence.util.DaoManager;

public class CategoryDAO extends DaoManager implements ICategoryDAO {

	private static final String GET_CATEGORY_BY_PARENT_ID_QUERY = "SELECT CategoryID ,ParentCategoryID, Name FROM shopdb.Category WHERE ParentCategoryID = ?;";
	private static final String GET_CATEGORY_BY_ID_QUERY = "SELECT CategoryID ,ParentCategoryID, Name FROM shopdb.Category WHERE CategoryID = ?;";
	
	@Override
	public List<Category> get() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Category findById(int id) throws SQLException {
		
		Connection conn = getConnection();
		
		Category category = null;
		
		PreparedStatement stmt = conn.prepareStatement(CategoryDAO.GET_CATEGORY_BY_ID_QUERY);
		stmt.setInt(1, id);
		ResultSet rs = stmt.executeQuery();
		
		if(rs.next()){
			category = new Category(
								rs.getInt("CategoryID"),
								rs.getInt("ParentCategoryID"),
								rs.getString("Name"));
		}
		
		closeConnection(conn, rs, stmt);
		
		return category;
	}

	@Override
	public List<Category> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Category> findByExample(Category exampleInstance) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int countAll() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int countByExample(Category exampleInstance) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Category save(Category entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void delete(int cartId) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Category create() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Category> findByParent(int parentId) throws SQLException {
		
		Connection conn = getConnection();
		
		List<Category> categoryList = new ArrayList<Category>();
		
		PreparedStatement stmt = conn.prepareStatement(CategoryDAO.GET_CATEGORY_BY_PARENT_ID_QUERY);
		stmt.setInt(1, parentId);
		ResultSet rs = stmt.executeQuery();
		
		while(rs.next()){
			categoryList.add(new Category(
								rs.getInt("CategoryID"),
								rs.getInt("ParentCategoryID"),
								rs.getString("Name")));
		}
		
		closeConnection(conn, rs, stmt);
		
		return categoryList;
	}

}
